<% layout('/layouts/default.html', {title: '出入库单管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(stInventoryBill.isNewRecord ? '新增出入库单' : '编辑出入库单')}
			</div>
			<div class="box-tools pull-right">
				<a href="#" class="btn btn-default" id="btn-src" ><i class="fa fa-filter"></i> ${text('源单')}
				</a>
				<a href="#" class="btn btn-default" id="btn-print" ><i class="fa fa-filter"></i> ${text('条码打印')}
				</a>
				<a href="#" class="btn btn-default" id="btn-approve" ><i class="fa fa-filter"></i> ${text('审核')}
				</a>
				<a href="#" class="btn btn-default" id="btn-revocation" ><i class="fa fa-filter"></i> ${text('弃审')}
				</a>
				<a href="#" class="btn btn-default" id="btn-save" ><i class="fa fa-filter"></i> ${text('保存')}
				</a>
				<div class="hide">
					<#form:listselect id="btn-src" title="采购单选择"

					url="${ctx}/st/stPurchaseBill/list" allowClear="false"
					checkbox="false"  callbackFuncName="listselectCallback"/>
				</div>
				<script>
					var aStatus=${stInventoryBill.approveState!"null"};
					approveBtnStatus(aStatus);
					function approveBtnStatus(status) {
						var $save = $("#btn-save");
						var $approve = $("#btn-approve");
						var $revocation = $("#btn-revocation");
						var $print = $("#btn-print");
						if (null == status ) {
							$save.show();
							$approve.hide();
							$revocation.hide();
						}
						if (2 == status) {
							$save.show();
							$approve.show();
							$revocation.hide();
						}
						if (4 == status) {
							$save.hide();
							$approve.hide();
							$revocation.show();
						}
					}
					function refresh(id) {
						location.replace("${ctx}/st/stInventoryBill/inventoryStatus?id="+id);
						// location.reload();
					}
					// 审核-------------------------------
					$("#btn-approve").click(function () {
						approveMain(4);
					});
					$("#btn-save").click(function () {
						$("#approveState").val(2);
						$("form").submit();
					});
					$("#btn-revocation").click(function () {
						approveMain(2)
					});
					var printStatus=1;
					$("#btn-print").click(function () {
						var printId=$('#stInventoryBillDetailDataGrid').dataGrid('getSelectRows');
						if(1!=printStatus){
							js.showMessage("请等待pdf生成");
							return;
						}
						$.ajax({
							url:"${ctx}/st/stInventoryBill/print",
							dataType:'json',
							type:'POST',
							data:{
								//请求参数
								printId: printId.join(",")
							},
							success:function(result){
								if(result.code !=1){
									js.showMessage("联系管理员");
									printStatus = 1;
									return;
								}
								window.open(result.data)
								printStatus = 1;
							}
						});
						printStatus = 2;
					});
					// 审核-------------------------------
					function approveMain(status) {
						var id = $("#id").val();
						$.ajax({
							url: "${ctx}/st/stInventoryBill/approve",
							dataType: 'json',
							type: 'POST',
							data: {
								//请求参数
								id: id,
								approveStatus: status,//具体是几还待确定
							},
							success: function (result) {
								if (1 != result.code) {
									js.showMessage(result.data);
									return;
								}
								js.showMessage("审核成功，此处替换成盖章");
								approveBtnStatus(status);
							}
						});
					}
					//---------------------------------------------------------------------------------------------------源单----------------------
					var addLength=0;
					function listselectCallback(id, act, index, layero, selectData){
						var selectLength = selectData.length;

						// var clickLength = addLength === 0 ? selectLength - 1 : selectLength;
						for (var i = 0; i < selectLength; i++) {
							$("#stInventoryBillDetailDataGridAddRowBtn").click();
						}
						for (var index in selectData) {
							var td_1 = $(($(($("#stInventoryBillDetailDataGrid").find("tr"))[parseInt(index) + 1 + addLength]).find('td'))[4]);//前面3行都什么啊
							//物料名称
							var item = selectData[index];

							var find = td_1.find(".form-control");
							find.val(item.materialName).trigger('change');
							td_1.find("input:hidden").val(item.materialName);
							//单位
							var td_unit=td_1.next();
							td_unit.find(".form-control").val(item.unit);
							// 批号
							var td_batch = td_unit.next();
							//仓位
							var td_warehouse=td_batch.next();
							td_warehouse.find(".form-control").val("1339023595280826368").trigger('change');//todo 不能写死
							//包装规格
							var td_pack_type = td_warehouse.next();
							td_pack_type.find(".form-control").val(item.materialRecord.packType);

							var td_number=td_pack_type.next();
							td_number.find(".form-control").val(item.number);

							//源单数量
							var td_src_bill_number = td_number.next();
							td_src_bill_number.find(".form-control").val(item.number);
							var primaryId = td_src_bill_number.next().next().next().next().next();
							primaryId.find(".form-control").val(item.id);

						}
						addLength += selectLength;
						if (id == 'parent' && (act == 'ok' || act == 'clear')){
							// var win = layero.iframeWindow();
							// log(win);    // 选择框内容的window对象
							// log(act);    // 回调活动事件（ok、clear、cancel）
							// log(index);  // layer的index
							// log(layero); // layer实例对象
							// log(selectData);  // 选择的节点数据
							// console.info("in", selectData);
						}
					}
					$(function () {
						$("#btn-src").click(function () {
							var supplierId=$("#supplierId").val();
							// console.info("supplier", supplierId);

							if(supplierId !=""){
								$("#btn-srcDiv").attr("data-url", "/js/a/st/stPurchaseBill/listSub?supplierId=" + supplierId);
								// console.info("url", $("#btn-srcDiv").data("url"));
								$("#btn-srcButton").click();
							}else{
								js.showMessage("请选择供应商");
							}

						});
						// $("#btn-src").click(function () {
						// 	var options = {
						// 		type: 2,
						// 		maxmin: true,
						// 		shadeClose: true,
						// 		title: '用户选择',
						// 		area: ['700px', '400px'],
						// 		content: '/js/a/sys/office/treeData?isLoadUser=true',
						// 		contentFormData: {
						// 			url: $('#buyerNameDiv').attr('data-url'),
						// 			checkbox: 'false',
						// 			chkboxType: "",
						// 			expandLevel: '-1',
						// 			selectCodes: $("#buyerNameCode").val(),
						// 			isReturnValue: 'false'
						// 		},
						// 		success: function(layero, index){
						// 			if ($(js.layer.window).width() < 300
						// 					|| $(js.layer.window).height() < 400){
						// 				js.layer.full(index);
						// 			}
						// 		},
						// 		btn: ['<i class="fa fa-check"></i> 确定'],
						// 		btn1: function(index, layero){
						// 			var body = layer.getChildFrame('body', index);//获取子页面内容
						// 			var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
						// 			var ids = iframeWin.test();
						// 			// body.find("#transmit").click();//执行子页面的方法
						// 			// body.find('input').val('Hi，我是从父页来的')
						// 			// $(".but_par").click(function(){
						// 			// 	alert(222);
						// 			// })
						// 			layer.close(index);//需要手动关闭窗口
						// 		}
						// 	};
						// 	options.btn.push('<i class="fa fa-eraser"></i> 清除');
						// 	options['btn'+options.btn.length] = function(index, layero){
						// 		$("#buyerNameCode").val('').change();
						// 		$("#buyerNameName").val('').change();
						// 		try{$('#buyerNameCode,#buyerNameName').resetValid();}catch(e){}
						// 		if(typeof treeselectCallback == 'function'){
						// 			treeselectCallback('buyerName', 'clear', index, layero);
						// 		}
						// 	};
						// 	options.btn.push('<i class="fa fa-close"></i> 关闭');
						// 	options['btn'+options.btn.length] = function(index, layero){
						// 		if(typeof treeselectCallback == 'function'){
						// 			treeselectCallback('buyerName', 'cancel', index, layero);
						// 		}
						// 	};
						// 	if(typeof treeselectOpen == 'function'){
						// 		if(treeselectOpen('buyerName', options) === false){
						// 			return true;
						// 		}
						// 	}
						// 	js.layer.open(options);
						// });
					});
				</script>
				<a href="#" class="btn btn-default" id="btnSetting" title="${text('设置')}"><i class="fa fa-navicon"></i></a>
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${stInventoryBill}" action="${ctx}/st/stInventoryBill/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>

				<#form:hidden path="id"/>
				<div class="row">
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('单据号')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:input path="billNo" maxlength="20" class="form-control"/>-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('单据日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="billDate" readonly="true" maxlength="20" class="form-control laydate"
									dataFormat="datetime" data-type="datetime" data-format="yyyy-MM-dd HH:mm"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('单据类别')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="billType" dictType="st_stock_in_bill_type" blankOption="true" class="form-control digits" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('入账日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="tallyDate" readonly="true" maxlength="20" class="form-control laydate"
									dataFormat="datetime" data-type="datetime" data-format="yyyy-MM-dd HH:mm"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('条码扫描')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="barCode" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('供应商')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="supplierId" items="${supplierList}" itemLabel="supplierFullName" blankOption="true" itemValue="id" class="form-control required" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('源单')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="primaryBillNo" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('出库或入库')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:select path="inOrOut" dictType="st_inventory_bill_type" blankOption="true" class="form-control digits" />-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
					<#form:hidden path="inOrOut"/>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('部门编码')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="deptCode" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('部门')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="deptName" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<#form:hidden path="approveState"/>
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('审批状态')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:select path="approveState" dictType="st_approve_state" blankOption="true" class="form-control digits" />-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('审批人编码')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:input path="approveManCode" maxlength="20" class="form-control"/>-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('审批人')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:input path="approveManName" maxlength="5" class="form-control"/>-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<h4 class="form-unit">${text('调拨单明细')}</h4>
				<div class="ml10 mr10">
					<table id="stInventoryBillDetailDataGrid"></table>
					<% if (hasPermi('st:stInventoryBill:edit')){ %>
						<a href="#" id="stInventoryBillDetailDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10" style="display: none"><i class="fa fa-plus"></i> ${text('增行')}</a>
					<% } %>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('st:stInventoryBill:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
//初始化调拨单明细DataGrid对象
$("#stInventoryBillDetailDataGrid").dataGrid({

	data: ${toJson(stInventoryBill.stInventoryBillDetailList)},
	datatype: "local", // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度

	// 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'id', editable:true, hidden:true},
		// {header:'${text("单据号")}', name:'billNo', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control'}},
		{header:'${text("物料名称")}', name:'materialName', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{materialName:'&nbsp;',id:''}], ${materialRecordList}),
				itemLabel: 'materialName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
					element.name="ignore_materialName";
					var name=element.name;
					$(element).attr("disabled",true);
					$(element).after("<input name='materialName' value='"+element.value+"' hidden>");
				}
			}
		},
		{header:'${text("单位")}', name:'unit', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'36', 'class':'form-control'}},
		{header:'${text("批号")}', name:'batchNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control'}},
		// {header:'${text("条码号")}', name:'barCode', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control'}},
		{header:'${text("仓位")}', name:'warehousePosition', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{warehouseName:'&nbsp;',id:''}], ${warehousePositionSettingList}),
				itemLabel: 'warehouseName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
				}
			}
		},
		{header:'${text("包装规格")}', name:'packType', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control'}},
		{header:'${text("数量")}', name:'number', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'8', 'class':'form-control digits'}},
		{header:'${text("源单数量")}', name:'sourceBillNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control',
				dataInit: function(element){
					$(element).attr("readonly", true);
				}
			}
		},
		{header:'${text("生产日期")}', name:'productDate', width:150,
			formatter:'date', formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			editable:true, edittype:'text', editoptions:{'class':'form-control laydate', 'readonly':'true',
				dataInit: function(element){
					laydate.render({elem:element, type:'datetime', format:'yyyy-MM-dd HH:mm'});
				}
			}
		},
		{header:'${text("保质期")}', name:'savedType', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'3', 'class':'form-control digits'}},
		{header:'${text("到期日期")}', name:'passDate', width:150,
			formatter:'date', formatoptions:{srcformat:'Y-m-d H:i:s',newformat:'Y-m-d H:i:s'},
			editable:true, edittype:'text', editoptions:{'class':'form-control laydate', 'readonly':'true',
				dataInit: function(element){
					laydate.render({elem:element, type:'datetime', format:'yyyy-MM-dd HH:mm'});
				}
			}
		},
		{header:'${text("生产厂家")}', name:'productMaker', width:100,
			editable:true, edittype:'select', editoptions:{'class':'form-control digits',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('st_product_maker')}),
				itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
				}
			}
		},
		{header:'${text("备注")}', name:'primaryId', width:100, editable:true, edittype:'textarea', editoptions:{'class':'form-control'},hidden: true},
		{header:'${text("备注")}', name:'remarks', width:150, editable:true, edittype:'textarea', editoptions:{'maxlength':'255', 'class':'form-control', 'rows':'1'}},

		{header:'${text("父 id")}', name:'parentId.id', editable:true, hidden:true},
			<% if(bill_type! =='diaobo'){ %>

		{header:'${text("库存数量")}', name:'inventoryNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'8', 'class':'form-control digits'}},
		{header:'${text("调出仓位")}', name:'allotOutWarehouse', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${warehousePositionSettingList}),
				itemLabel: 'warehouseName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
				}
			}
		},
		{header:'${text("调入仓位")}', name:'allotInWarehouse', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${warehousePositionSettingList}),
				itemLabel: 'warehouseName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
				}
			}
		},
		{header:'${text("调拨数量")}', name:'allotNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'8', 'class':'form-control digits'}},
		<% } %>
		{header:'${text("操作")}', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
			var actions = [];
			if (val == 'new'){
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stInventoryBillDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
				// actions.push('<a href="#" class="del" onclick="$(\'#stInventoryBillDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}else{
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stInventoryBillDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
				// actions.push('<a href="#" class="del" onclick="$(\'#stInventoryBillDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],
	shrinkToFit: false,
	// 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 0,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#stInventoryBillDetailDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowInitData: {id: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据

	// 编辑表格的提交数据参数
	editGridInputFormListName: 'stInventoryBillDetailList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,id,billNo,materialName,unit,batchNumber,barCode,warehousePosition,packType,number,productDate,savedType,passDate,productMaker,remarks,parentId.id,inventoryNumber,allotOutWarehouse,allotInWarehouse,allotNumber,sourceBillNumber,primaryId', // 提交数据列表的属性字段

	// 加载成功后执行事件
	showCheckbox: true,
	ajaxSuccess: function(data){
		// console.info("data",data);
		addLength=data.rows.length;
	}
});
</script>
<script>
$("#inputForm").validate({
	submitHandler: function(form){
		js.ajaxSubmitForm($(form), function(data){
			var id = data.data.id;
			refresh(id);
			// $("#id").val(id);
			// approveBtnStatus(data.data.approveState);
			js.showMessage(data.message);
			// if(data.result == Global.TRUE){
			// 	js.closeCurrentTabPage(function(contentWindow){
			// 		contentWindow.page();
			// 	});
			// }
		}, "json");
    }
});
</script>